package com.xxadmin.usercenter.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xxadmin.common.constant.Iconstant;
import com.xxadmin.common.dto.PageInfoDTO;
import com.xxadmin.common.util.clone.CopyUtils;
import com.xxadmin.common.util.page.PageUtils;
import com.xxadmin.usercenter.dao.OauthClientDetailsDao;
import com.xxadmin.usercenter.domain.OauthClientDetails;
import com.xxadmin.usercenter.dto.OauthClientDetailsDTO;
import com.xxadmin.usercenter.dto.OauthUserQueryDTO;
import com.xxadmin.usercenter.service.OauthClientDetailsService;
import com.xxadmin.usercenter.util.BCryptPasswordEncoderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * OauthClient 实现类
 *
 * @author:chenming
 * @date:2018/8/23
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
public class OauthClientDetailsServiceImpl implements OauthClientDetailsService{

    @Autowired
    private OauthClientDetailsDao oauthClientDetailsDao;

    @Override
    public void add(OauthClientDetailsDTO oauthClientDetails) {
        OauthClientDetails clientDetails = CopyUtils.copyBean(oauthClientDetails,OauthClientDetails.class);

        clientDetails.setClientSecret("{bcrypt}" + BCryptPasswordEncoderUtil.encoder(clientDetails.getClientSecret()));
        clientDetails.setCreateTime(new Date());
        clientDetails.setStatus(Iconstant.STATUS_ENABLED);

        oauthClientDetailsDao.insertSelective(clientDetails);
    }

    @Override
    public void update(OauthClientDetailsDTO oauthClientDetails) {
        OauthClientDetails clientDetails = CopyUtils.copyBean(oauthClientDetails,OauthClientDetails.class);

        clientDetails.setClientSecret("{bcrypt}" + BCryptPasswordEncoderUtil.encoder(clientDetails.getClientSecret()));
        clientDetails.setUpdateTime(new Date());

        oauthClientDetailsDao.updateByPrimaryKeySelective(clientDetails);
    }

    @Override
    public PageInfoDTO<OauthClientDetailsDTO> listOauthUserDetail(OauthUserQueryDTO queryDTO) {

        PageHelper.startPage(queryDTO.getPageNum(),queryDTO.getPageSize());

        Page<OauthClientDetailsDTO> page = oauthClientDetailsDao.selectOauthUserDetail(queryDTO);

        return PageUtils.getPageInfoDTO(page,OauthClientDetailsDTO.class);
    }

    @Override
    public OauthClientDetails getOauthClientDetails(String clientId) {
        return oauthClientDetailsDao.selectByPrimaryKey(clientId);
    }
}
